#!/usr/bin/python

from cgi import parse_qsl
import sys; sys.path.insert(0, ".")
from genedex import Genedex
from genedex.plot import gplot
import os
import sys
from cStringIO import StringIO


def wrapplication(port=3000):
    """decorator to wrap a wsgi application() to allow it to be called
        via CGI, WSGI, or as a standalone server.
    """
    def wrapper(wsgi_app):
        if 'TERM' in os.environ:
            print "serving on port: %i" % port
            print """\
    try a url like:
        http://localhost:%i/?genedex=/abs/path/to/gendex/object&start=1&stop=16384&width=756&height=256
    where the path does _not_ include the file extension
                  """ % port
            try:
                from cherrypy import wsgiserver
                print "using cherrypy server."
                s = wsgiserver.CherryPyWSGIServer(('0.0.0.0', port), [('/', wsgi_app)], server_name='')
                try: s.start()
                except KeyboardInterrupt: print "stopping server ...  "; s.stop()
            except Exception, e:
                print e
                from wsgiref.simple_server import make_server
                print "using wsgiref server."
                make_server('', port, wsgi_app).serve_forever()

        elif 'CGI' in os.environ.get('GATEWAY_INTERFACE',''):
            import wsgiref.handlers
            wsgiref.handlers.CGIHandler().run(wsgi_app)
        else:
            #wsgi_app
            pass
    return wrapper

@wrapplication(3000)
def application(environ, start_response):
    qs = dict(parse_qsl(environ['QUERY_STRING']))

    gdx_path = qs['genedex']
    print >>sys.stderr, gdx_path
    if not os.path.exists(gdx_path + '.idx'):
        start_response("200 OK", [('Content-Type', 'text/plain')])
        return [ 'error: give path to existing genedex file (no extension)' ]


    start_response("200 OK", [('Content-Type', 'image/png')])
    gdx = Genedex(gdx_path)
    s = StringIO() 
    start = int(qs.get('start', 1))
    stop  = int(qs.get('stop' , 32768))
    bounds = {'start': start, 'stop': stop}
    w, h = int(qs.get('width', 756)), int(qs.get('height', 256))
    gplot(gdx, bounds, filename=s, width=w, height=h)
    s.seek(0)
    return [ s.read() ] 
